package com.maybach.web.controller.order;

import com.audi.dubbo.api.admin.models.AdminModel;
import com.audi.dubbo.api.common.Result;
import com.audi.dubbo.api.common.enums.CarStandardEnum;
import com.maybach.common.BizResult;
import com.maybach.common.dto.LoanOrderDTO;
import com.maybach.common.dto.UserInfoDTO;
import com.maybach.common.enums.ActLogActorNameEnum;
import com.maybach.common.enums.ActLogBizTypeEnum;
import com.maybach.common.enums.BaseConstants;
import com.maybach.common.enums.order.FinanceBizTypeEnum;
import com.maybach.common.enums.order.LoanOrderStatusEnum;
import com.maybach.common.enums.user.UserStatusEnum;
import com.maybach.common.model.CarSnapDO;
import com.maybach.common.model.FinanceFlowDO;
import com.maybach.common.model.LoanOrderDO;
import com.maybach.core.ao.*;
import com.maybach.core.dubbo.consumer.adapter.AdminServiceDubooAdapter;
import com.maybach.core.form.finance.FinanceDetailForm;
import com.maybach.core.form.finance.FinanceForm;
import com.maybach.core.form.order.*;
import com.maybach.core.form.user.UserQueryForm;
import com.maybach.core.manager.CommonEnumManager;
import com.maybach.core.manager.LoanOrderManager;
import com.maybach.util.*;
import com.maybach.util.query.support.PageResult;
import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.LoanOrderStatusTool;
import com.maybach.web.framework.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by houenxun on 16/2/23.
 */
@Controller
@RequestMapping(value = "/loanOrder/")
public class LoanOrderController {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoanOrderAO loanOrderAO;
    @Autowired
    LoanOrderManager loanOrderManager;
    @Autowired
    private UserAO userAO;
    @Autowired
    private BrandAndSeriesAO brandAndSeriesAO;
    @Autowired
    private FinanceFlowAO financeFlowAO;
    @Autowired
    protected CommonEnumManager commonEnumManager;
    @Autowired
    UserMsgAO userMsgAO;
    @Autowired
    AdminServiceDubooAdapter adminServiceDubooAdapter;
    @Autowired
    ActLogAO actLogAO;


    /**
     * 添加页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "add")
    public String add(@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (!model.containsAttribute("addLoanOrderForm")) {
            AddLoanOrderForm addLoanOrderForm = new AddLoanOrderForm();
            model.addAttribute(addLoanOrderForm);
        }
        return "loanOrder/add";
    }


    /**
     * 添加user
     *
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doAdd", method = RequestMethod.POST)
    public String doAdd(@Valid AddLoanOrderForm addLoanOrderForm, BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            loanOrderAO.addLoanOrder(addLoanOrderForm);
        } catch (Exception e) {
            logger.error("添加订单保失败addLoanOrderForm="+addLoanOrderForm, e);
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }

        return "result";
    }

    /**
     * 订单宝列表
     *
     * @param queryLoanOrderForm
     * @param bindingResult
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView loanOrderListViewAction(@ModelAttribute("queryLoanOrderForm") QueryLoanOrderForm queryLoanOrderForm, BindingResult bindingResult) {
        ModelAndView mav = new ModelAndView();
        if (null == queryLoanOrderForm) {
            queryLoanOrderForm = new QueryLoanOrderForm();
        }
        try {
            queryLoanOrderForm.setIsQueryAll(false);
            BizResult result = loanOrderAO.queryLoanOrders(queryLoanOrderForm);
            if (result.isSuccess()) {
                PageResult<LoanOrderDTO> pageResult = (PageResult<LoanOrderDTO>) result.getResultData();
                mav.addObject("paginationResult", pageResult);
                mav.addObject("query", queryLoanOrderForm);
                mav.addObject("loanOrderStatusTool", new LoanOrderStatusTool());
                mav.setViewName("loanOrder/list");
            } else {
                mav.addObject(WebConstants.RESULT_CODE_KEY, result.getResultCode());
                mav.setViewName("result");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            mav.addObject(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
            mav.setViewName("result");
        }
        return mav;
    }

    @RequiresAuthentication
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public void exportLoanOrderList(@ModelAttribute("queryLoanOrderForm") QueryLoanOrderForm queryLoanOrderForm, HttpServletResponse response, HttpServletRequest request) {
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream;charset=utf-8");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "订单宝列表" + sdf.format(new Date()) + ".xlsx";
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE")) {
                response.addHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", " ") + "\"");
            } else if (null != agent && -1 != agent.indexOf("Firefox")) {
                response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + "\"");
            } else if (null != agent && -1 != agent.indexOf("Safari")) {
                response.addHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", " ") + "\"");
            } else {
                response.addHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", " ") + "\"");
            }
            if (null == queryLoanOrderForm) {
                queryLoanOrderForm = new QueryLoanOrderForm();
            }
            queryLoanOrderForm.setIsQueryAll(true);
            ExportLoanOrderForm exportLoanOrderForm = new ExportLoanOrderForm();
            exportLoanOrderForm.setQueryLoanOrderForm(queryLoanOrderForm);
            exportLoanOrderForm.setOutputStream(outputStream);
            loanOrderAO.exportLoanOrders(exportLoanOrderForm);
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }

            }
        }
    }

    /**
     * 订单宝详情
     *
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public ModelAndView loanOrderDetailAction(@PathVariable("id") Long id) {
        ModelAndView mav = new ModelAndView();
        try {
            BizResult result = loanOrderAO.queryLoanOrderById(id);
            if (result.isSuccess()) {
                mav.addObject("loanOrderTool", new LoanOrderStatusTool());
                mav.addObject("loanOrderDTO", result.getResultData());
                ImgUrlUtil imgUrlUtil = new ImgUrlUtil();
                mav.addObject("imgUrlUtil", imgUrlUtil);
                mav.setViewName("loanOrder/detail");
            } else {
                mav.addObject(WebConstants.RESULT_CODE_KEY, result.getResultCode());
                mav.setViewName("result");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            mav.addObject(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
            mav.setViewName("result");
        }
        return mav;
    }


    /**
     * 订单宝供应商编辑页面
     *
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "providerEdit/{id}", method = RequestMethod.GET)
    public String loanOrderProviderEditViewAction(@PathVariable("id") Long id, ModelMap modelMap) {
        modelMap.addAttribute(WebConstants.REDIRECT_URL_KEY, "/loanOrder/detail/" + id);
        try {
            BizResult bizResult = loanOrderAO.editLoanOrderProviderView(id);
            if (null != bizResult && bizResult.isSuccess()) {
                if (!modelMap.containsAttribute("editLoanOrderPartnerForm")) {
                    modelMap.addAttribute("editLoanOrderPartnerForm", bizResult.getResultData());
                }
                modelMap.addAttribute("financeFlowDOs", bizResult.getData().get("financeFlowDOs"));
                return "loanOrder/edit/providerInfoEdit";
            } else {
                modelMap.addAttribute(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
                return "result";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            modelMap.addAttribute(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
        }
        return "result";
    }

    /**
     * 编辑订单宝供应商信息请求
     *
     * @param editLoanOrderPartnerForm
     * @param bindingResult
     * @param redirectUrl
     * @param redirectAttributes
     * @param model
     * @param request
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doProviderEdit", method = RequestMethod.POST)
    public String doPartnerEditAction(@Valid @ModelAttribute("editLoanOrderPartnerForm") EditLoanOrderPartnerForm editLoanOrderPartnerForm, BindingResult bindingResult,
                                      @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
                                      RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            BizResult bizResult = loanOrderAO.editLoanOrderProvider(editLoanOrderPartnerForm);
            model.addAttribute(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        return "result";
    }

    /**
     * 查询供应商
     *
     * @param queryPartnerForm
     * @param bindingResult
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "providerList", method = RequestMethod.GET)
    public ModelAndView providerListViewAction(@ModelAttribute("queryPartnerForm") QueryPartnerForm queryPartnerForm, BindingResult bindingResult) {
        ModelAndView mav = new ModelAndView();
        try {
            if (null == queryPartnerForm) {
                queryPartnerForm = new QueryPartnerForm();
            }
            BizResult bizResult = loanOrderAO.queryPartnerList(queryPartnerForm);
            if (null != bizResult && bizResult.isSuccess()) {
                mav.setViewName("loanOrder/providerList");
                mav.addObject("query", queryPartnerForm);
                mav.addObject("paginationResult", bizResult.getResultData());
                mav.addObject("loanOrderTool", new LoanOrderStatusTool());
            } else {
                mav.addObject(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
                mav.setViewName("result");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            mav.addObject(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
            mav.setViewName("result");
        }
        return mav;
    }

    /**
     * 审批页面
     *
     * @param typeName
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "approve/{typeName}/{id}", method = RequestMethod.GET)
    public String approveViewAction(@PathVariable("typeName") String typeName, @PathVariable("id") Long id, ModelMap modelMap) {
        modelMap.addAttribute(WebConstants.REDIRECT_URL_KEY, "/loanOrder/detail/" + id);
        try {
            if (StringUtil.isEmpty(typeName) || null == id || id < 1L) {
                modelMap.addAttribute(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.PARAM_ERROR);
                return "result";
            } else {
                ApproveLoanOrderForm form = new ApproveLoanOrderForm();
                form.setOrderId(id);
                form.setTypeName(typeName);
                BizResult bizResult = loanOrderAO.approveImgsView(form);
                if (null != bizResult && bizResult.isSuccess()) {
                    if (!modelMap.containsAttribute("approveLoanOrderForm")) {
                        form = (ApproveLoanOrderForm) bizResult.getResultData();
                        modelMap.addAttribute("approveLoanOrderForm", form);
                    }
                    return "loanOrder/audit/imgs";
                } else {
                    modelMap.addAttribute(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
                    return "result";
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            modelMap.addAttribute(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
        }
        return "result";
    }

    @RequiresAuthentication
    @RequestMapping(value = "doApprove", method = RequestMethod.POST)
    public String doContractApproveAction(@Valid @ModelAttribute("approveLoanOrderForm") ApproveLoanOrderForm approveLoanOrderForm, BindingResult bindingResult,
                                          @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
                                          RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            BizResult bizResult = loanOrderAO.approveLoanOrderImgs(approveLoanOrderForm);
            model.addAttribute(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        return "result";
    }


    /**
     * 编辑页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit/orderLoanInfoEdit")
    public String orderLoanInfoEdit(@RequestParam(value = "id") Long id, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        BizResult bizResult = loanOrderAO.queryEditLoanOrderById(id);
        setModel(model, bizResult);
        return "loanOrder/edit/orderLoanInfoEdit";
    }

    private void setModel(ModelMap model, BizResult bizResult) {
        if (bizResult.isSuccess()) {
            model.addAttribute("loanOrder", bizResult.getData().get("result"));
        }
        // 获取业务经理

        Map<String, String> map =  getUsersByDubbo("b2bManager");

        model.addAttribute("admin", map);
        // 获取所有品牌
        Result result = this.getAllBrand();
        if (result.isSuccess()) {
            model.addAttribute("brandList", result.getData());
        }
        // 获取车源枚举
        Map<String, Integer> carTypesMap = new HashMap<>();
        for (CarStandardEnum carStandardEnum : CarStandardEnum.values()) {
            carTypesMap.put(carStandardEnum.getDesc(), carStandardEnum.getStatus());
        }
        model.addAttribute("carTypes", carTypesMap);

        EditLoanOrderForm editLoanOrderForm = (EditLoanOrderForm) bizResult.getData().get("result");
        if (editLoanOrderForm.getCarSnapDO() != null) {
            CarSnapDO carSnapDO = editLoanOrderForm.getCarSnapDO();
            Long brandId = carSnapDO.getBrandId();
            model.addAttribute("selectSeriesList", this.getSeriesByBrandId(brandId).getData());
            Long seriesId = carSnapDO.getSeriesId();
            model.addAttribute("selectModelList", this.getModelBySeriId(seriesId).getData());
        }
    }

    private Map<String,String> getUsersByDubbo(String role){
        List<AdminModel> list = adminServiceDubooAdapter.getAdminModelByRoleCode(role);

        Map<String, String> map = new HashMap<String, String>();
        for(AdminModel model : list){
            map.put(model.getAdminId()+"", getName(model));
        }
        return map;
    }

    private String getName(AdminModel model){
        if(StringUtil.isNotBlank(model.getExtattr())){
            return model.getExtattr();
        }
        return model.getNick();
    }

    /**
     * 编辑页面-财务信息-保证金
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit/financeInfoEditMargin")
    public String financeInfoEditMargin(@RequestParam(value = "outOrderId") Long outOrderId, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        getFinanceInfoByBizType(outOrderId, FinanceBizTypeEnum.Margin, model);
        return "loanOrder/edit/financeInfoEditMargin";
    }

    private void getFinanceInfoByBizType(Long outOrderId, FinanceBizTypeEnum financeBizTypeEnum, ModelMap model) {
        try {
            List<FinanceFlowDO> ls = financeFlowAO.queryByBizType(outOrderId, financeBizTypeEnum.name());
            if (!CollectionUtils.isEmpty(ls)) {
                FinanceForm financeForm = new FinanceForm();
                List<String> payWays = new ArrayList<>();
                List<String> payTimes = new ArrayList<>();
                List<String> amounts = new ArrayList<>();
                List<String> chargeNos = new ArrayList<>();
                List<String> memos = new ArrayList<>();
                List<String> profImgs = new ArrayList<>();
                for (FinanceFlowDO financeFlowDO : ls) {
                    payWays.add(financeFlowDO.getPayWay());
                    payTimes.add(CalendarUtil.toString(financeFlowDO.getPayTime(),CalendarUtil.TIME_PATTERN));
                    amounts.add(PriceUtil.formatNoGroup(financeFlowDO.getAmount()));
                    chargeNos.add(financeFlowDO.getChargeNo());
                    memos.add(financeFlowDO.getMemo());
                    String prof=financeFlowDO.getProfImgs();
                    if(StringUtils.isNotBlank(prof)){
                        List<String> lp = ImgUrlUtil.parseList(prof);
                        profImgs.add(MaybachUtil.transferString(lp,","));
                    }
                }
                financeForm.setPayWay(payWays);
                financeForm.setPayTime(payTimes);
                financeForm.setChargeNo(chargeNos);
                financeForm.setMemo(memos);
                financeForm.setProfImgs(profImgs);
                financeForm.setAmount(amounts);
                model.put("financeForm", financeForm);
                model.put("ls", ls);
            }
            //如果是垫资还款页面增加一块显示
            if(FinanceBizTypeEnum.LoanRepay==financeBizTypeEnum){
                LoanOrderDO loanOrderDO=loanOrderAO.queryById(outOrderId);
                    if(loanOrderDO!=null){
                       model.addAttribute(loanOrderDO);
                }
            }

            model.put("loanOrderId", outOrderId);
            model.put("bizType", financeBizTypeEnum.name());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑页面-财务信息-付款
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit/financeInfoEditPay")
    public String financeInfoEditPay(@RequestParam(value = "outOrderId") Long outOrderId, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        getFinanceInfoByBizType(outOrderId, FinanceBizTypeEnum.Pay, model);
        return "loanOrder/edit/financeInfoEditPay";
    }

    /**
     * 编辑页面-财务信息-垫资还款
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit/financeInfoEditLoanRepay")
    public String financeInfoEditLoanRepay(@RequestParam(value = "outOrderId") Long outOrderId, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        getFinanceInfoByBizType(outOrderId, FinanceBizTypeEnum.LoanRepay, model);
        return "loanOrder/edit/financeInfoEditLoanRepay";
    }


    /**
     * 新增保证金/付款/垫资  通过bizType区分
     *
     * @param financeForm
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequiresRoles("adminFinance")
    @RequestMapping(value = "edit/doFinanceInfoEditByBizType")
    public String doEditFinance(FinanceForm financeForm,FinanceDetailForm financeDetailForm, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        //添加日志
        addLog(financeForm);
        //保存财务信息
        financeFlowAO.addFinanceByBizType(financeForm);
        LoanOrderDO loanOrderDO = loanOrderAO.queryById(financeForm.getLoanOrderId());
        if (FinanceBizTypeEnum.LoanRepay.name().equals(financeForm.getBizType())) {
            if(financeDetailForm!=null&&financeDetailForm.getLoanOrderId()==null){
                financeDetailForm.setLoanOrderId(financeForm.getLoanOrderId());
            }
            loanOrderAO.editLoanOrderFinanceDetail(financeDetailForm);
            try {
                loanOrderDO.setStatus(LoanOrderStatusEnum.finished.getCode());
                //改订单宝状态
                loanOrderManager.updateByPrimaryKeySelective(loanOrderDO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(FinanceBizTypeEnum.Pay.name().equals(financeForm.getBizType())){
            //发消息通知
            try {
                userMsgAO.payToProvider(loanOrderDO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getDetailString(financeForm.getLoanOrderId());
    }

    private void addLog(FinanceForm financeForm) {
        try {
            if(FinanceBizTypeEnum.Margin.name().equals(financeForm.getBizType())){
                actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,financeForm.getLoanOrderId(),"财务编辑保证金信息", ActLogActorNameEnum.updateFinanceMargin);
            }
            else if(FinanceBizTypeEnum.Pay.name().equals(financeForm.getBizType())){
                actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,financeForm.getLoanOrderId(),"财务编辑付款信息", ActLogActorNameEnum.updateFinancePay);
            }
            else if(FinanceBizTypeEnum.LoanRepay.name().equals(financeForm.getBizType())){
                actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,financeForm.getLoanOrderId(),"财务编辑垫资信息", ActLogActorNameEnum.updateFinanceLoanRepay);
            }
        } catch (Exception e) {
            logger.error("error in addLog,form:"+financeForm.toString());
        }
    }


    /*
     * 编辑订单宝
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit/{id}")
    public String edit(@PathVariable("id") Long id, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (!model.containsAttribute("editLoanOrderForm")) {
            EditLoanOrderForm editLoanOrderForm = new EditLoanOrderForm();
            editLoanOrderForm.setId(id);
            model.addAttribute(editLoanOrderForm);
        }
        return "loanOrder/edit/orderLoanInfoEdit";
    }

    /**
     * 添加user
     *
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doEdit", method = RequestMethod.POST)
    public String doEdit(@Valid EditLoanOrderForm editLoanOrderForm, BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        try {
            loanOrderAO.editLoanOrder(editLoanOrderForm);
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }

        return "result";
    }


    /**
     * 申请者列表
     *
     * @param userQueryForm
     * @param bindingResult
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "applicant", method = RequestMethod.GET)
    public String applicant(@ModelAttribute("userQueryForm") UserQueryForm userQueryForm, BindingResult bindingResult, ModelMap model) {
        if (null == userQueryForm) {
            userQueryForm = new UserQueryForm();
        }
        if (!model.containsAttribute("userQueryForm")) {
            model.addAttribute(userQueryForm);
        }
        try {
            if (CollectionUtils.isEmpty(userQueryForm.getStatus())) {
                userQueryForm.setStatus(Arrays.asList(UserStatusEnum.normal.getCode(), UserStatusEnum.disable.getCode()));
            }
            PageResult<UserInfoDTO> result = userAO.queryAuthenticateUser(userQueryForm);
            model.addAttribute("pageResult", result);
            return "loanOrder/applicant";

        } catch (Exception e) {
            logger.error("", e);
            return "result";
        }
    }

    @RequiresAuthentication
    @RequestMapping(value = "closeLoanOrder/{id}", method = RequestMethod.GET)
    public String closeLoanOrderViewAction(@PathVariable("id") Long id, ModelMap modelMap) {
        if (!modelMap.containsAttribute("closeLoanOrderForm")) {
            CloseLoanOrderForm closeLoanOrderForm = new CloseLoanOrderForm();
            closeLoanOrderForm.setId(id);
            modelMap.addAttribute("closeLoanOrderForm", closeLoanOrderForm);
        }
        return "loanOrder/closeOrder";
    }

    @RequiresAuthentication
    @RequestMapping(value = "doCloseLoanOrder", method = RequestMethod.POST)
    public String closeLoanOrderAction(@Valid @ModelAttribute("closeLoanOrderForm") CloseLoanOrderForm closeLoanOrderForm,
                                        BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
                                        RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            BizResult bizResult = loanOrderAO.closeLoanOrder(closeLoanOrderForm);
            model.addAttribute(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        return "result";
    }

    @RequiresAuthentication
    @RequestMapping(value = "deleteLoanOrder/{id}", method = RequestMethod.GET)
    public String deleteLoanOrderViewAction(@PathVariable("id") Long id, ModelMap modelMap) {
        if (!modelMap.containsAttribute("closeLoanOrderForm")) {
            CloseLoanOrderForm closeLoanOrderForm = new CloseLoanOrderForm();
            closeLoanOrderForm.setId(id);
            modelMap.addAttribute("closeLoanOrderForm", closeLoanOrderForm);
        }
        return "loanOrder/deleteOrder";
    }

    @RequiresAuthentication
    @RequestMapping(value = "doDeleteLoanOrder", method = RequestMethod.POST)
    public String deleteLoanOrderAction(@Valid @ModelAttribute("closeLoanOrderForm") CloseLoanOrderForm closeLoanOrderForm,
                                        BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
                                        RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            BizResult bizResult = loanOrderAO.deleteLoanOrder(closeLoanOrderForm);
            model.addAttribute(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        return "result";
    }
    /**
     * 根据品牌ID获取车系信息
     *
     * @param brandId
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @RequestMapping(value = "getSeriesByBrandId/{brandId}", method = RequestMethod.POST)
    public Result getSeriesByBrandId(@PathVariable("brandId") Long brandId) {
        return brandAndSeriesAO.getSeriesByBrandId(brandId);
    }

    /**
     * 获取所有的品牌
     *
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @RequestMapping(value = "getAllBrand", method = RequestMethod.POST)
    public Result getAllBrand() {
        return brandAndSeriesAO.getAllBrand();
    }

    @RequiresAuthentication
    @ResponseBody
    @RequestMapping(value = "getModelBySeriesId", method = RequestMethod.GET)
    public Result getModelBySeriId(@RequestParam("seriesId") Long seriId) {
        return brandAndSeriesAO.getModelsBySeriesId(seriId);
    }

    /**
     * 查询操作日志
     *
     * @param id
     * @param actLogForm
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "actLog/{id}", method = RequestMethod.GET)
    public ModelAndView actLogViewAction(@PathVariable("id") Long id, @ModelAttribute("actLogForm") QueryLoanOrderActLogForm actLogForm) {
        ModelAndView mav = new ModelAndView();
        if (actLogForm == null) {
            actLogForm = new QueryLoanOrderActLogForm();
        }
        actLogForm.setId(id);
        try {
            BizResult bizResult = loanOrderAO.queryLoanOrderActLogs(actLogForm);
            if (null != bizResult && bizResult.isSuccess()) {
                mav.setViewName("loanOrder/orderActLog");
                mav.addObject("pageResult", bizResult.getResultData());
                mav.addObject("form", actLogForm);
            } else {
                mav.setViewName("result");
                mav.addObject(WebConstants.RESULT_CODE_KEY, bizResult.getResultCode());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            mav.setViewName("result");
            mav.addObject(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
        }
        return mav;
    }


    /**
     * 新增、修改、成功挑战到订单宝详情
     *
     * @param outOrderId
     * @return
     */
    private String getDetailString(Long outOrderId) {
        String detail = WebConstants.REDIRECT_PREFIX + "/loanOrder/detail/";
        detail += outOrderId;
        return detail;
    }

    /**
     * 发送委托函页面
     * * @param id
     * @return
     */
    @RequestMapping(value = "sendLetter/{id}", method = RequestMethod.GET)
    public String sendLetter(@PathVariable("id") Long id, ModelMap model) {
        BizResult bizResult = loanOrderAO.getLetterInfo(id);
        if (bizResult.isSuccess()) {
            model.addAttribute("letterInfo", bizResult.getData().get("result"));
        }
        return "loanOrder/sendLetter";
    }

    /**
     * 发送委托函
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "checkSendLetter/{id}", method = RequestMethod.POST)
    public Object checkSendLetter(@PathVariable("id") Long id) {
        BizResult bizResult = loanOrderAO.checkSendLetter(id);
        return bizResult;
    }

    /**
     * 生成在线合同
     *
     * @return
     */
    @RequestMapping(value = "createContract/{id}", method = RequestMethod.GET)
    public String createContract(@PathVariable("id") Long id, ModelMap model) {
        BizResult bizResult = loanOrderAO.createContract(id);
        if (bizResult.isSuccess()) {
            model.addAttribute("contract", bizResult.getData().get("result"));
        }
        return "loanOrder/createContract";
    }

    /**
     * 下载线上合同
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "downloadContract/{id}", method = RequestMethod.GET)
    public Object downloadContract(@PathVariable("id") Long id, HttpServletResponse response, HttpServletRequest request) {
        String fontPath = request.getSession().getServletContext().getRealPath("/fonts");
        loanOrderAO.createContractPDF(fontPath, id, response);
        return null;
    }

    /**
     * 打印请款单
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "printContractPaper/{id}", method = RequestMethod.GET)
    public String printPaper(@PathVariable("id") Long id, ModelMap model) {
        BizResult result = loanOrderAO.getContractInfo(id);
        if (result.isSuccess()) {
            model.addAttribute("ContractInfo", result.getData().get("result"));
        }
        return "loanOrder/printContractPaper";
    }


    /**
     * 关闭订单
     *
     * @param
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "closeOrder")
    public String closeOrder() {
        return "loanOrder/closeOrder";
    }

    /**
     * 删除订单
     *
     * @param
     * @return
     */
    @RequestMapping(value = "deleteOrder")
    public String deleteOrder() {
        return "loanOrder/deleteOrder";
    }

}
